package com.qifenqian.turbot.config

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.os.Handler
import java.util.concurrent.CopyOnWriteArrayList

/**
 * @author H
 * @createTime 2019/1/16 15:55
 * @description 应用处于前后台状态的监听 一般用于webSocket的断线重连(应用回到前台的时候需要重连)
 * @see https://blog.csdn.net/zly921112/article/details/72973054/
 * @since
 */
class ForegroundCallbacks : Application.ActivityLifecycleCallbacks {

    companion object {
        const val delay: Long = 600L  //
        private var instance: ForegroundCallbacks? = null
        fun init(application: Application): ForegroundCallbacks {
            if (instance == null) {
                instance = ForegroundCallbacks()
                application.registerActivityLifecycleCallbacks(instance)
            }
            return instance!!
        }

        fun getInstance(application: Application): ForegroundCallbacks {
            if (instance == null) {
                init(application)
            }
            return instance!!
        }

        fun getInstance(context: Context): ForegroundCallbacks {
            if (instance == null) {
                val applicationContext = context.applicationContext
                if (applicationContext is Application) {
                    init(applicationContext)
                }
                throw IllegalStateException("Foreground is not initialised and cannot obtain the Application object")
            }
            return instance!!
        }

        fun getInstance(): ForegroundCallbacks {
            return instance!!
        }
    }

    private var isForeground: Boolean = false
    private var isPaused: Boolean = true
    private var mHandler: Handler? = null
    private var mListeners: CopyOnWriteArrayList<Listener> = mutableListOf<Listener>() as CopyOnWriteArrayList
    private var mRunnable = Runnable {
        if (isForeground && isPaused) {
            isForeground = false
            for (listener in mListeners) {
                try {
                    listener.onBecameBackground()
                } catch (e: Exception) {
                }
            }
        }
    }

    fun isForeground(): Boolean {
        return isForeground
    }

    fun isBackground(): Boolean {
        return !isForeground
    }

    fun addListener(listener: Listener) {
        mListeners.add(listener)
    }

    fun removeListener(listener: Listener) {
        mListeners.remove(listener)
    }

    override fun onActivityResumed(activity: Activity?) {
        isPaused = false
        val wasBackground = !isForeground
        isForeground = true
        mHandler!!.removeCallbacks(mRunnable)
        if (wasBackground) {
            for (listener in mListeners) {
                try {
                    listener.onBecameForeground()
                } catch (e: Exception) {
                }
            }
        }
    }

    override fun onActivityPaused(activity: Activity?) {
        isPaused = true
        mHandler!!.removeCallbacks(mRunnable)
        mHandler!!.postDelayed(mRunnable, delay)
    }

    override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}
    override fun onActivityStarted(activity: Activity?) {}
    override fun onActivityStopped(activity: Activity?) {}
    override fun onActivityDestroyed(activity: Activity?) {}
    override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}

    interface Listener {
        fun onBecameForeground()

        fun onBecameBackground()
    }
}